package com.tuo.controller;

import com.tuo.beans.Detail;
import com.tuo.beans.enums.Algorithm;
import com.tuo.service.DetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tuo on 2016/1/9.
 */
@Controller
public class DetailController {
    @Autowired
    DetailService service;


    @ResponseBody
    @RequestMapping("detail")
    public Map<String, Object> detail(long orderId, int page, int rows) {
        Map<String, Object> map = new HashMap<String, Object>();
        Detail detail = new Detail();
        detail.setOrdId(orderId);
        List<Detail> details = null;
        try {
            details = this.service.query(detail);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        map.put("totle", details.size());
        List<Detail> list = new ArrayList<Detail>();
        for (int i = (page - 1) * rows; i < details.size() && i < (page * rows); i++) {
            list.add(details.get(i));
        }
        map.put("rows", list);
        return map;
    }

    @ResponseBody
    @RequestMapping("saveDetail")
    public Map<String, String> SaveDetail(Detail detail, long orderId, String algValue) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            detail.setAlgorithm(Algorithm.get(algValue));
            detail.setOrdId(orderId);
            service.save(detail);
            map.put("message", "success");
        } catch (Throwable e) {
            map.put("errorMsg", e.getMessage());
        }
        return map;
    }

    @ResponseBody
    @RequestMapping("algorithms")
    public List<Map<String, String>> getAlgorithms() {
        List<Map<String, String>> maps = new ArrayList<Map<String, String>>();
        for (Algorithm algorithm : Algorithm.values()) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("value", algorithm.getValue());
            map.put("text", algorithm.getDescription());
            maps.add(map);
        }
        return maps;
    }
}
